package com.hanlink.dsp.ui.view;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.util.DisplayMetrics;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.qztech.utils.YzDebug;

/**
 * Copyright (C), 深圳市东乘电子科技有限公司
 * Carate By YangZhong
 */
public class CenterTextButton extends androidx.appcompat.widget.AppCompatButton {
    private String text;
    private Rect mTextRext;
    public CenterTextButton(@NonNull Context context) {
        this(context, null);
    }

    public CenterTextButton(@NonNull Context context, @Nullable AttributeSet attrs) {
        this(context, attrs,0);
    }

    public CenterTextButton(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mTextRext = new Rect();
    }


    @Override
    public void setText(CharSequence text, BufferType type) {
        if(text == null){
            this.text = null;
        }else{
            this.text = text.toString();
        }
        postInvalidate();
    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);
        final int height = bottom - top;
        Paint.FontMetrics metrics = getPaint().getFontMetrics();
        int offset = (int) (metrics.bottom - metrics.top);
        DisplayMetrics displayMetrics = getContext().getResources().getDisplayMetrics();
        setTextSize(height/displayMetrics.scaledDensity/1.1f);

    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        Paint.FontMetrics fontMetrics = getPaint().getFontMetrics();
        getPaint().getTextBounds(text, 0, text.length(),mTextRext);
        canvas.drawText(text, 0,text.length(), (getWidth()-mTextRext.width())/2, getHeight()/2 - fontMetrics.bottom/2 - fontMetrics.top/2, getPaint());
    }
}
